<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 建筑管理
 *
 * @icon fa fa-building
 */
class Building extends Backend
{
    protected $model = null;
    protected $relationSearch = true;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Building;
    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $list = $this->model
                ->with(['companies'])
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);

            $result = array("total" => $list->total(), "rows" => $list->items());
            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }

                    $data = $this->request->post("");
                    //拼接地址
                    $params['prov'] = $data['prov'];
                    $params['city'] = $data['city'];
                    $params['region'] = $data['region'];
                    $params['street'] = $data['street'];

                    //如果未填写经纬度,则根据地址解析
                    if (!$params['lat'] || !$params['lng']) {
                        $address = $params['prov'] . $params['city'] . $params['region'] . $params['street'] . $params['address'];
                        $result = getGeo($address);
                        if ($result['status'] == 0) {
                            exception('获取经纬度失败，请选择正确的地址');
                        }
                        $params['lat'] = $result['lat'];
                        $params['lng'] = $result['lng'];
                    }

                    $result = $this->model->allowField(true)->save($params);
                    //保存关联公司
                    if (isset($params['company_ids']) && $params['company_ids']) {
                        $company_ids = explode(',', $params['company_ids']);
                        $relationData = [];
                        foreach ($company_ids as $company_id) {
                            $relationData[] = [
                                'building_id' => $this->model->id,
                                'company_id' => $company_id,
                                'createtime' => time(),
                                'updatetime' => time(),
                                'weigh' => 0
                            ];
                        }
                        if ($relationData) {
                            Db::name('company_building')->insertAll($relationData);
                        }
                    }
                    
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }

                    $data = $this->request->post("");
                    //拼接地址
                    $params['prov'] = $data['prov'];
                    $params['city'] = $data['city'];
                    $params['region'] = $data['region'];
                    $params['street'] = $data['street'];

                    //如果未填写经纬度,则根据地址解析
                    if (!$params['lat'] || !$params['lng']) {
                        $address = $params['prov'] . $params['city'] . $params['region'] . $params['street'] . $params['address'];
                        $result = getGeo($address);
                        if ($result['status'] == 0) {
                            exception('获取经纬度失败，请选择正确的地址');
                        }
                        $params['lat'] = $result['lat'];
                        $params['lng'] = $result['lng'];
                    }

                    $result = $row->allowField(true)->save($params);

                    //更新关联公司
                    if (isset($params['company_ids'])) {
                        //删除原有关联
                        Db::name('company_building')->where('building_id', $ids)->delete();
                        if ($params['company_ids']) {
                            $company_ids = explode(',', $params['company_ids']);
                            $relationData = [];
                            foreach ($company_ids as $company_id) {
                                $relationData[] = [
                                    'building_id' => $ids,
                                    'company_id' => $company_id,
                                    'createtime' => time(),
                                    'updatetime' => time(),
                                    'weigh' => 0
                                ];
                            }
                            if ($relationData) {
                                Db::name('company_building')->insertAll($relationData);
                            }
                        }
                    }

                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }

        //获取已关联的公司ID
        $company_ids = Db::name('company_building')
            ->where('building_id', $ids)
            ->column('company_id');
        $this->view->assign('company_ids', implode(',', $company_ids));
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        if ($ids) {
            $pk = $this->model->getPk();
            $adminIds = $this->getDataLimitAdminIds();
            if (is_array($adminIds)) {
                $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            $list = $this->model->where($pk, 'in', $ids)->select();

            $count = 0;
            Db::startTrans();
            try {
                foreach ($list as $k => $v) {
                    //删除关联数据
                    Db::name('company_building')->where('building_id', $v->id)->delete();
                    $count += $v->delete();
                }
                Db::commit();
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($count) {
                $this->success();
            } else {
                $this->error(__('No rows were deleted'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }

    /**
     * 关联公司
     */
    public function company($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    // 检查是否已经关联
                    $exists = Db::name('company_building')
                        ->where('building_id', $ids)
                        ->where('company_id', $params['company_id'])
                        ->find();
                    
                    if ($exists) {
                        exception(__('该公司已关联'));
                    }

                    $result = Db::name('company_building')->insert([
                        'building_id' => $ids,
                        'company_id' => $params['company_id'],
                        'weigh' => $params['weigh'],
                        'createtime' => time(),
                        'updatetime' => time()
                    ]);
                    Db::commit();
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }

        //获取已关联的公司
        $companies = Db::name('company_building')
            ->alias('cb')
            ->join('company c', 'c.id = cb.company_id')
            ->where('cb.building_id', $ids)
            ->field('cb.*, c.name as company_name')
            ->order('cb.weigh DESC, cb.id DESC')
            ->select();

        $this->view->assign('companies', $companies);
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 删除关联公司
     */
    public function delcompany($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        if ($ids) {
            Db::startTrans();
            try {
                $result = Db::name('company_building')->delete($ids);
                Db::commit();
                if ($result) {
                    $this->success();
                } else {
                    $this->error(__('No rows were deleted'));
                }
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }
} 